﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace AugustVisual
{
    public class TextBlockX : FrameworkElement
    {
        public event DependencyPropertyChangedEventHandler TextChanged;
        public TextBlockX()
        {

        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(TextBlockX), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, TextPropertyChanged));

        public static void TextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

            ((TextBlockX)d).OnTextChanged(d, e);
        }

        public virtual void OnTextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            TextChanged?.Invoke(sender, e);
        }



        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            //drawingContext.DrawRectangle(Brushes.Gray, null, new Rect(this.RenderSize));
            drawingContext.DrawText(new FormattedText(Text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), 20, Brushes.Black, VisualTreeHelper.GetDpi(this).PixelsPerDip), new Point(0, 0));
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            //return base.MeasureOverride(availableSize);
            FormattedText formattedText = new FormattedText(
                                   Text,
                                   CultureInfo.CurrentUICulture,
                                   FlowDirection.LeftToRight,
                                   new Typeface("Arial"),
                                   20,
                                   Brushes.Black,
                                   VisualTreeHelper.GetDpi(this).PixelsPerDip
                                   );
            Size size = new Size(formattedText.Width, formattedText.Height);
            //this.Measure(availableSize);
            //Size size1 = new Size(40, 10);
            return size;
        }
    }
}
